<!-- 文件名: app/templates/users.html -->
{% extends "base.html" %}

{% block title %}用户列表 - 社交媒体监控{% endblock %}

{% block page_title %}用户列表{% endblock %}

{% block content %}
<div class="card mb-4">
    <div class="card-header">
        <h5>导入用户</h5>
    </div>
    <div class="card-body">
        <div class="row mb-3">
            <div class="col-md-6">
                <h6>通过Excel批量导入</h6>
                <p class="small text-muted">Excel文件应包含以下列：
                    <strong>账号博主名称</strong>(选填) 、
                    <strong>主页链接</strong>(必填)、
                    <strong>平台</strong>(选填)、
                    <strong>内容</strong>(必填)
                </p>
                <form id="excelUploadForm" class="row g-3">
                    <div class="col-auto">
                        <input type="file" class="form-control" id="excelFile" name="file" accept=".xlsx,.xls">
                    </div>
                    <div class="col-auto">
                        <button type="button" class="btn btn-primary" onclick="uploadExcel()">导入Excel</button>
                    </div>
                    <div class="col-auto">
                        <a href="/api/template/excel" class="btn btn-outline-secondary">
                            <i class="bi bi-file-earmark-excel"></i> 下载模板
                        </a>
                    </div>
                </form>
            </div>
            <div class="col-md-6">
                <h6>手动添加用户</h6>
                <div class="btn-group" role="group">
                    <button class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#tiktokModal">
                        <i class="bi bi-tiktok"></i> 添加TikTok
                    </button>
                    <button class="btn btn-outline-danger" data-bs-toggle="modal" data-bs-target="#douyinModal">
                        <i class="bi bi-music-note-list"></i> 添加抖音
                    </button>
                     <button class="btn btn-outline-success" data-bs-toggle="modal" data-bs-target="#kuaishouModal">
                        <i class="bi bi-kuaishou"></i> 添加快手
                    </button>
                    <button class="btn btn-outline-warning" data-bs-toggle="modal" data-bs-target="#instagramModal">
                        <i class="bi bi-instagram"></i> 添加Instagram
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="mb-3">
    <div class="d-flex flex-wrap gap-2">
        <button type="button" class="btn btn-success" onclick="checkAllUpdates(null)">检查所有用户更新</button>
        <button type="button" class="btn btn-outline-primary" onclick="checkAllUpdates('tiktok')">检查TikTok用户</button>
        <button type="button" class="btn btn-outline-danger" onclick="checkAllUpdates('douyin')">检查抖音用户</button>
        <button type="button" class="btn btn-outline-success" onclick="checkAllUpdates('kuaishou')">检查快手用户</button>
        <button type="button" class="btn btn-outline-warning" onclick="checkAllUpdates('instagram')">检查Instagram用户</button>
    </div>
</div>

<div class="mt-3">
    <button id="batchDeleteBtn" class="btn btn-danger" style="display: none;" onclick="batchDelete()">批量删除</button>
</div>

<!-- 搜索和筛选 -->
<div class="card mb-3">
    <div class="card-body">
        <form method="get" action="/users" class="row g-3">
            <div class="col-md-3">
                <label for="search" class="form-label">搜索用户名</label>
                <input type="text" class="form-control" id="search" name="search" value="{{ search or '' }}">
            </div>
            <div class="col-md-3">
                <label for="platform" class="form-label">平台</label>
                <select class="form-select" id="platform" name="platform">
                    <option value="">全部平台</option>
                    <option value="tiktok" {% if platform==
                    'tiktok' %}selected{% endif %}>TikTok</option>
                    <option value="douyin" {% if platform==
                    'douyin' %}selected{% endif %}>抖音</option>
                    <option value="instagram" {% if platform==
                    'instagram' %}selected{% endif %}>Instagram</option>
                    <option value="kuaishou" {% if platform==
                    'kuaishou' %}selected{% endif %}>快手</option>
                </select>
            </div>
            <div class="col-md-2">
                <label for="category" class="form-label">分类</label>
                <select class="form-select" id="category" name="category">
                    <option value="">全部分类</option>
                    {% for cat in categories %}
                    <option value="{{ cat }}" {% if category== cat %}selected{% endif %}>{{ cat }}</option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-2">
                <label for="per_page" class="form-label">每页显示</label>
                <select class="form-select" id="per_page" name="per_page">
                    <option value="10" {% if pagination.per_page== 10 %}selected{% endif %}>10</option>
                    <option value="20" {% if pagination.per_page== 20 %}selected{% endif %}>20</option>
                    <option value="50" {% if pagination.per_page== 50 %}selected{% endif %}>50</option>
                    <option value="100" {% if pagination.per_page== 100 %}selected{% endif %}>100</option>
                </select>
            </div>
            <div class="col-md-2 d-flex align-items-end">
                <button type="submit" class="btn btn-primary me-2">搜索</button>
                <a href="/users" class="btn btn-secondary">重置</a>
            </div>
        </form>
    </div>
</div>

<!-- 用户展示 -->
<div class="table-responsive">
    <table class="table table-striped table-sm">
        <thead>
        <tr>
            <th><input type="checkbox" id="selectAll" onclick="toggleSelectAll()"></th>
            <th>平台</th>
            <th>用户名</th>
            <th>头像</th>
            <th>分类</th>
            <th>视频数</th>
            <th>检查状态</th>
            <th>最后检查时间</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        {% for user in users %}
        <tr>
            <td><input type="checkbox" class="user-checkbox" value="{{ user.id }}" onchange="updateBatchDeleteButton()">
            </td>
            <td>
                <span class="badge platform-{{ user.platform }}">{{ user.platform }}</span>
            </td>
            <td>{{ user.username }}</td>
            <td>
                {% if user.profile_pic %}
                <img src="{{ user.profile_pic }}" width="40" height="40" class="rounded-circle">
                {% else %}
                <img src="/static/default-avatar.png" width="40" height="40" class="rounded-circle">
                {% endif %}
            </td>
            <td>
                {% if user.category %}
                <span class="badge bg-info text-dark">{{ user.category }}</span>
                {% else %}
                <span class="badge bg-light text-dark">未分类</span>
                {% endif %}
            </td>
            <td>{{ user.last_video_count }}</td>
            <td>{{ "开" if user.is_open else "关" }}</td>
            <td>{{ user.last_checked }}</td>
            <td>
                <div class="btn-group btn-group-sm">
                    <button type="button" class="btn btn-warning"
                            onclick="editCategory({{ user.id }}, '{{ user.username }}', '{{ user.category }}', '{{user.is_open}}')">编辑
                    </button>
                    <button type="button" class="btn btn-primary btn-sm"
                            onclick="checkUserUpdate({{ user.id }}, '{{ user.username }}')">检查
                    </button>
                    <a href="/users/{{ user.id }}" class="btn btn-info">详情</a>
                    <a href="/videos?user_id={{ user.id }}" class="btn btn-secondary">视频</a>
                    <a href="#" class="btn btn-danger"
                       onclick="deleteUser({{ user.id }}, '{{ user.username }}'); return false;">删除</a>
                </div>
            </td>
        </tr>
        {% endfor %}
        </tbody>
    </table>
</div>

<!-- 分页导航 -->
{% if pagination.pages > 1 %}
<nav aria-label="Page navigation">
    <ul class="pagination justify-content-center">
        <li class="page-item {% if pagination.page == 1 %}disabled{% endif %}">
            <a class="page-link"
               href="?page=1&per_page={{ pagination.per_page }}{% if platform %}&platform={{ platform }}{% endif %}{% if search %}&search={{ search }}{% endif %}{% if category %}&category={{ category }}{% endif %}"
               aria-label="First">
                <span aria-hidden="true">首页</span>
            </a>
        </li>
        <li class="page-item {% if pagination.page == 1 %}disabled{% endif %}">
            <a class="page-link"
               href="?page={{ pagination.page - 1 }}&per_page={{ pagination.per_page }}{% if platform %}&platform={{ platform }}{% endif %}{% if search %}&search={{ search }}{% endif %}{% if category %}&category={{ category }}{% endif %}"
               aria-label="Previous">
                <span aria-hidden="true">上一页</span>
            </a>
        </li>

        {% set start_page = (pagination.page - 2) if (pagination.page - 2) > 0 else 1 %}
        {% set end_page = (start_page + 4) if (start_page + 4) <= pagination.pages else pagination.pages %}
        {% if end_page - start_page < 4 and start_page > 1 %}
        {% set start_page = (end_page - 4) if (end_page - 4) > 0 else 1 %}
        {% endif %}

        {% for p in range(start_page, end_page + 1) %}
        <li class="page-item {% if p == pagination.page %}active{% endif %}">
            <a class="page-link"
               href="?page={{ p }}&per_page={{ pagination.per_page }}{% if platform %}&platform={{ platform }}{% endif %}{% if search %}&search={{ search }}{% endif %}{% if category %}&category={{ category }}{% endif %}">{{
                p }}</a>
        </li>
        {% endfor %}

        <li class="page-item {% if pagination.page == pagination.pages %}disabled{% endif %}">
            <a class="page-link"
               href="?page={{ pagination.page + 1 }}&per_page={{ pagination.per_page }}{% if platform %}&platform={{ platform }}{% endif %}{% if search %}&search={{ search }}{% endif %}{% if category %}&category={{ category }}{% endif %}"
               aria-label="Next">
                <span aria-hidden="true">下一页</span>
            </a>
        </li>
        <li class="page-item {% if pagination.page == pagination.pages %}disabled{% endif %}">
            <a class="page-link"
               href="?page={{ pagination.pages }}&per_page={{ pagination.per_page }}{% if platform %}&platform={{ platform }}{% endif %}{% if search %}&search={{ search }}{% endif %}{% if category %}&category={{ category }}{% endif %}"
               aria-label="Last">
                <span aria-hidden="true">末页</span>
            </a>
        </li>
    </ul>
</nav>
<div class="text-center">
    <small class="text-muted">共 {{ pagination.total }} 条记录，当前第 {{ pagination.page }}/{{ pagination.pages }}
        页</small>
</div>
{% endif %}

<!-- 添加TikTok用户模态框 -->
<div class="modal fade" id="tiktokModal" tabindex="-1" aria-labelledby="tiktokModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="tiktokModalLabel">添加TikTok用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="tiktokForm" action="/api/users/tiktok" method="post">
                    <div class="mb-3">
                        <label for="tiktokUsername" class="form-label">用户名 (不带@的用户名)</label>
                        <input type="text" class="form-control" id="tiktokUsername" name="username" required>
                    </div>
                    <div class="mb-3">
                        <label for="tiktokCategory" class="form-label">分类</label>
                        <input type="text" class="form-control" id="tiktokCategory" name="category"
                               placeholder="例如：足球集锦、治愈风格等">
                        <div class="form-text">可选，用于分类整理视频</div>
                    </div>
                    <div class="mb-3">
                        <label for="tiktokSequence" class="form-label">序号</label>
                        <input type="text" class="form-control" id="tiktokSequence" name="sequence"
                               placeholder="对标账号的序号">
                        <div class="form-text">可选，用于建对标文件夹</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitForm('tiktokForm')">添加</button>
            </div>
        </div>
    </div>
</div>

<!-- 添加抖音用户模态框 -->
<div class="modal fade" id="douyinModal" tabindex="-1" aria-labelledby="douyinModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="douyinModalLabel">添加抖音用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="douyinForm" action="/api/users/douyin" method="post">
                    <div class="mb-3">
                        <label for="douyinSecUid" class="form-label">用户ID (sec_uid)</label>
                        <input type="text" class="form-control" id="douyinSecUid" name="sec_uid" required>
                        <div class="form-text">例如：MS4wLjABAAAARmgSomN5R5...</div>
                    </div>
                    <div class="mb-3">
                        <label for="douyinCategory" class="form-label">分类</label>
                        <input type="text" class="form-control" id="douyinCategory" name="category"
                               placeholder="例如：足球集锦、治愈风格等">
                        <div class="form-text">可选，用于分类整理视频</div>
                    </div>
                    <div class="mb-3">
                        <label for="douyinSequence" class="form-label">序号</label>
                        <input type="text" class="form-control" id="douyinSequence" name="sequence"
                               placeholder="对标账号的序号">
                        <div class="form-text">可选，用于建对标文件夹</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitForm('douyinForm')">添加</button>
            </div>
        </div>
    </div>
</div>

<!-- 添加Instagram用户模态框 -->
<div class="modal fade" id="instagramModal" tabindex="-1" aria-labelledby="instagramModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="instagramModalLabel">添加Instagram用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="instagramForm" action="/api/users/instagram" method="post">
                    <div class="mb-3">
                        <label for="instagramUsername" class="form-label">用户名</label>
                        <input type="text" class="form-control" id="instagramUsername" name="username" required>
                    </div>
                    <div class="mb-3">
                        <label for="instagramCategory" class="form-label">分类</label>
                        <input type="text" class="form-control" id="instagramCategory" name="category"
                               placeholder="例如：足球集锦、治愈风格等">
                        <div class="form-text">可选，用于分类整理视频</div>
                    </div>
                    <div class="mb-3">
                        <label for="instagramSequence" class="form-label">序号</label>
                        <input type="text" class="form-control" id="instagramSequence" name="sequence"
                               placeholder="对标账号的序号">
                        <div class="form-text">可选，用于建对标文件夹</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitForm('instagramForm')">添加</button>
            </div>
        </div>
    </div>
</div>

<!-- 添加快手用户模态框 -->
<div class="modal fade" id="kuaishouModal" tabindex="-1" aria-labelledby="kuaishouModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="kuaishouModalLabel">添加快手用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="kuaishouForm" action="/api/users/kuaishou" method="post">
                    <div class="mb-3">
                        <label for="kuaishouUsername" class="form-label">用户ID</label>
                        <input type="text" class="form-control" id="kuaishouUsername" name="username" required>
                        <div class="form-text">例如：3xcy8r7qs5...</div>
                    </div>
                    <div class="mb-3">
                        <label for="kuaishouCategory" class="form-label">分类</label>
                        <input type="text" class="form-control" id="kuaishouCategory" name="category"
                               placeholder="例如：足球集锦、治愈风格等">
                        <div class="form-text">可选，用于分类整理视频</div>
                    </div>
                    <div class="mb-3">
                        <label for="kuaishouSequence" class="form-label">序号</label>
                        <input type="text" class="form-control" id="kuaishouSequence" name="sequence"
                               placeholder="对标账号的序号">
                        <div class="form-text">可选，用于建对标文件夹</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitForm('kuaishouForm')">添加</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑分类模态框 -->
<div class="modal fade" id="editCategoryModal" tabindex="-1" aria-labelledby="editCategoryModalLabel"
     aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editCategoryModalLabel">编辑用户分类</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editCategoryForm">
                    <input type="hidden" id="editUserId" name="user_id">
                    <div class="mb-3">
                        <label for="editUserName" class="form-label">用户名</label>
                        <input type="text" class="form-control" id="editUserName" disabled>
                    </div>
                    <div class="mb-3">
                        <label for="editCategory" class="form-label">分类</label>
                        <input type="text" class="form-control" id="editCategory" name="category"
                               placeholder="例如：足球集锦、治愈风格等">
                        <div class="form-text">为空则表示删除分类</div>
                    </div>
                    <!-- 添加 is_open 字段 -->
                    <div class="mb-3">
                        <label for="editIsOpen" class="form-label">是否开启</label>
                        <input type="checkbox" class="form-check-input" id="editIsOpen" name="is_open">
                        <div class="form-text">勾选表示开启，未勾选表示关闭</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="updateCategory()">保存</button>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block scripts %}
<script>
    function checkUserUpdate(userId, username) {
        if (confirm(`确定要检查用户 "${username}" 的更新吗？`)) {
            // 显示加载状态
            fetch(`/api/check-updates?user_id=${userId}&redirect=false`, {
                method: 'GET'
            })
                .then(response => response.json())
                .then(data => {
                    if (data.client_id) {
                        // 跳转到进度页面
                        window.location.href = `/progress?client_id=${data.client_id}`;
                    } else {
                        alert(data.detail || `开始检查用户 "${username}" 的更新`);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('启动检查失败: ' + error.detail);
                });
        }
    }

    function checkAllUpdates(platform) {
    // 确定平台名称显示
    let platformName = platform ?
        (platform === 'tiktok' ? 'TikTok' :
         platform === 'douyin' ? '抖音' :
         platform === 'instagram' ? 'Instagram' :
         platform === 'kuaishou' ? '快手' : '') : '所有';

    // 确认对话框
    if (!confirm(`确定要开始检查${platformName}用户的更新吗？`)) {
        return;
    }

    // 找到相应的按钮并更新状态
    const btn = platform ?
        document.querySelector(`button[onclick="checkAllUpdates('${platform}')"]`) :
        document.querySelector('button[onclick="checkAllUpdates(null)"]');

    const originalText = btn.textContent;
    btn.textContent = '检查中...';
    btn.disabled = true;

    // 构建API请求URL
    const url = platform ?
        `/api/check-updates?redirect=false&platform=${platform}` :
        '/api/check-updates?redirect=false';

    // 发送请求
    fetch(url, { method: 'GET' })
        .then(response => response.json())
        .then(data => {
            btn.textContent = originalText;
            btn.disabled = false;

            if (data.client_id) {
                // 跳转到进度页面
                window.location.href = `/progress?client_id=${data.client_id}`;
            } else {
                alert(data.message || '检查已开始');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            btn.textContent = originalText;
            btn.disabled = false;
            alert('启动检查失败: ' + error.message);
        });
}

    function uploadExcel() {
        const fileInput = document.getElementById('excelFile');

        if (!fileInput.files || fileInput.files.length === 0) {
            alert('请先选择Excel文件');
            return;
        }

        // 显示加载状态
        const uploadBtn = document.querySelector('#excelUploadForm button');
        const originalText = uploadBtn.textContent;
        uploadBtn.textContent = '上传中...';
        uploadBtn.disabled = true;

        const formData = new FormData();
        formData.append('file', fileInput.files[0]);

        fetch('/api/upload', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                // 恢复按钮状态
                uploadBtn.textContent = originalText;
                uploadBtn.disabled = false;

                if (data.message) {
                    // 成功消息
                    alert(data.message);
                    // 可选：刷新页面显示新导入的用户
                    setTimeout(() => location.reload(), 1000);
                } else if (data.detail) {
                    // 错误消息
                    alert('上传失败: ' + data.detail);
                } else {
                    alert('上传成功');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                uploadBtn.textContent = originalText;
                uploadBtn.disabled = false;
                alert('上传失败: ' + error.message);
            });
    }

    function deleteUser(userId, username) {
        if (confirm(`确定要删除用户 "${username}" 吗？`)) {
            fetch(`/api/users/${userId}`, {
                method: 'DELETE',
            })
                .then(response => {
                    if (response.ok) {
                        alert('用户删除成功');
                        location.reload();
                    } else {
                        alert('删除失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('删除失败');
                });
        }
    }

    function toggleSelectAll() {
        const selectAllCheckbox = document.getElementById('selectAll');
        const userCheckboxes = document.getElementsByClassName('user-checkbox');

        for (let checkbox of userCheckboxes) {
            checkbox.checked = selectAllCheckbox.checked;
        }

        updateBatchDeleteButton();
    }

    function updateBatchDeleteButton() {
        const userCheckboxes = document.getElementsByClassName('user-checkbox');
        const batchDeleteBtn = document.getElementById('batchDeleteBtn');

        let checkedCount = 0;
        for (let checkbox of userCheckboxes) {
            if (checkbox.checked) {
                checkedCount++;
            }
        }

        batchDeleteBtn.style.display = checkedCount > 0 ? 'inline-block' : 'none';
        batchDeleteBtn.textContent = `批量删除 (${checkedCount})`;
    }

    function batchDelete() {
        const userCheckboxes = document.getElementsByClassName('user-checkbox');
        const selectedIds = [];

        for (let checkbox of userCheckboxes) {
            if (checkbox.checked) {
                selectedIds.push(parseInt(checkbox.value));
            }
        }

        if (selectedIds.length === 0) {
            return;
        }

        if (confirm(`确定要删除选中的 ${selectedIds.length} 个用户吗？此操作将同时删除这些用户的所有视频！此操作不可恢复！`)) {
            // 使用批量删除API
            fetch('/api/users-batch', {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(selectedIds),
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    alert(data.message);
                    location.reload();
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('批量删除失败: ' + error.message);
                });
        }
    }

    function submitForm(formId) {
        const form = document.getElementById(formId);

        // 手动提交表单
        fetch(form.action, {
            method: form.method,
            body: new FormData(form),
        })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    alert('添加失败: ' + data.error);
                } else {
                    alert('添加成功');
                    location.reload();
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('添加失败');
            });
    }

    function editCategory(userId, username, category, is_open) {
        // 填充模态框表单
        document.getElementById('editUserId').value = userId;
        document.getElementById('editUserName').value = username;
        document.getElementById('editCategory').value = category || '';

        // 填充 is_open 字段
        document.getElementById('editIsOpen').checked = (is_open === "True");  // 如果是字符串 "True"，勾选 checkbox

        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('editCategoryModal'));
        modal.show();
    }


    function updateCategory() {
        const userId = document.getElementById('editUserId').value;
        const category = document.getElementById('editCategory').value;
        const is_open = document.getElementById('editIsOpen').checked ? true : false;


        fetch(`/api/users/${userId}/category`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(
                {
                    category: category,
                    is_open: is_open
                }),
        })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    alert('更新失败: ' + data.error);
                } else {
                    alert('资料已更新');
                    location.reload();
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('更新失败');
            });
    }
</script>
{% endblock %}